import {
	defineStore
} from "pinia";

// #ifdef APP
import {
	Weigh,
	Print as startPrint,
	ToSet,
	USBScanCode as initUSBScanCode,
	USBReadCard as initUSBReadCard
} from "@/uni_modules/ys-uts";
import {
	Camera as camera
} from "@/uni_modules/ys-camera"
import {log} from "@/uni_modules/ys-uts/utssdk/app-android/CommonUtils.uts"
import icon from "../uni_modules/uview-plus/libs/config/props/icon";
import {
	getUsbDeviceList,
	getSerialPortDeviceList,
	PeripheralConfig1 as PeripheralConfig
} from "@/uni_modules/ys-uts/";
// #endif
export const devicesStore = defineStore("devices", {
	state: () => {
		return {
			devices: {
				Weigh: {
					value: 0.0,
					isStable: false,
					matched: null,
					configProject: []
				},
				ScanCode: {
					value: '',
					matched: null
				},
				IC: {
					value: '',
					matched: null
				},
				Print: {
					matched: null
				}
			},
			setting: {
				Weigh: {
					// scaleIsUsb: true, //串口还是usb，true为usb
					// scaleAddress: "/dev/ttyZC2", //串口匹配时用的地址，usb时无用
				},
				ScanCode: {
					matchCode: [], //扫码器默认匹配码[VendorId_ProductId]13547_5378
				},
				IC: {
					matchCode: [], //刷卡器默认匹配码[VendorId_ProductId]65535_53
				},
				Print: {
					open: true, //是否开启打印，默认开启
					printChargeRow: false, //打印是否添加换行，默认换行
					printBase64Pic: false, //是否打印二维码，默认打印
					printNumber: 3, //订单打印票据次数，默认3次
				},
				Camera: {
					list: [], //网络摄像头匹配列表
					openFrontPhoto: true, //录入收货单时前置摄像头是否开启拍照，默认开启
					openWatermark: true, //网络摄像头是否开启称重水印，默认开启
					tempPhoto: '', //前置摄像头拍照临时路径保存
				},
				scanCodeAndICisNative: true,//读卡器扫码器是否用原生方法读取数值，否则使用usb匹配
			},
			PeripheralConfig: uni.getStorageSync("PeripheralConfig")
		};
	},
	getters: {},
	actions: {
		// 云端设置同步功能
		async syncSettings() {
			try {
				const systemInfo = uni.getSystemInfoSync()
				console.log('云端设置同步功能systemInfo:',systemInfo)
				
				// 获取用户详情并确保它是一个对象
				let userdetail = uni.getStorageSync("userdetail");
				if (typeof userdetail === 'string') {
					try {
						userdetail = JSON.parse(userdetail || '{}');
					} catch (e) {
						userdetail = {};
					}
				} else if (!userdetail) {
					userdetail = {
						// id: 0,
						// currentpackid: 0,
						// username: "未登录",
						// mobile: null,
						// packname: null
					};
				}
				// console.log('云端设置同步参数:',{
				// 	mac: getMac(),
				// 	deviceId: uni.getSystemInfoSync().deviceId,
				// 	peripheralConfig: uni.getStorageSync("PeripheralConfig"),
				// 	appName: systemInfo.appName,
				// 	appId: systemInfo.appId,
				// 	systemInfo: systemInfo,
				// 	settings: this.setting,
				// 	Authorization: uni.getStorageSync('Authorization'),
				// 	userdetail: userdetail,
				// 	packname: userdetail?.packname,
				// 	log: log.get(),
				// 	isUpDate: true
				// })
				const res = await uniCloud.callFunction({
					name: 'updateSetting',
					data: {
						mac: getMac(),
						deviceId: uni.getSystemInfoSync().deviceId,
						peripheralConfig: uni.getStorageSync("PeripheralConfig"),
						appName: systemInfo.appName,
						appId: systemInfo.appId,
						systemInfo: systemInfo,
						settings: this.setting,
						userdetail: userdetail,
						Authorization: uni.getStorageSync('Authorization'),
						packname: userdetail?.packname,
						log: log.get(),
						isUpDate: true
					}
				});

				console.log('设置同步成功', res);
				return true;
			} catch (e) {
				console.error('设置同步失败', e);
				uni.showToast({
					title: '设置同步失败，请检查网络',
					icon: 'none'
				});
				return false;
			}
		},
		// 获取云端设置
		async fetchCloudSettings() {
			console.log('获取云端设置前查询参数',{
				mac: getMac()
			})
			try {
				const res = await uniCloud.callFunction({
					name: 'getSetting',
					data: {
						deviceId: uni.getSystemInfoSync().deviceId,
						mac: getMac()
					}
				});

				if (res.result.data && res.result.data.length > 0) {
					const cloudSettings = res.result.data[0];
					console.log('从云端获取设置:', cloudSettings);

					if (cloudSettings) {
						if (cloudSettings.isUpDate == false) {
							// cloudSettings.isUpDate = true
							console.log('从云端恢复设置:', cloudSettings);
							uni.setStorageSync('setting', cloudSettings?.settings);
							let setting = uni.getStorageSync('setting')
							// 更优的实现方式
							for (const category in this.setting) {
								if (setting[category]) {
									this.setting[category] = {
										...this.setting[category],
										...setting[category]
									};
								}
							}
							uni.setStorageSync('setting', this.setting)

							if (cloudSettings.peripheralConfig) {
								uni.setStorageSync('PeripheralConfig', cloudSettings.peripheralConfig);
							}
							console.log('已经恢复完成的设置setting：', this.setting)
							console.log('已经恢复完成的设置PeripheralConfig：', uni.getStorageSync('PeripheralConfig'))
						}
					}
					return cloudSettings;
				}
				return null;
			} catch (e) {
				console.error('获取云端设置失败', e);
				uni.showToast({
					title: '获取云端设置失败',
					icon: 'none'
				});
				return null;
			}
		},
		// 摄像头绑定
		cameraSetting() {
			// console.log('开始设置摄像头...')
			return new Promise((resolve, reject) => {
				camera.search((list) => {
					console.log('camerasearch', JSON.stringify(list));
					resolve(list)
				}, (data) => {
					console.log('err', JSON.stringify(data));
					reject(data)
				});
			})
		},
		//摄像头抓拍
		CapturePicture(opt) {
			console.log('摄像头链接', this.setting.Camera.list)
			let photoArr = [] //摄像头截图数组

			return new Promise((resolve, reject) => {
				// 获取所有网络摄像头的src字符串，合并为一个数组
				let srcs = []
				this.setting.Camera.list.forEach((item) => {
					srcs.push(item.src)
				})

				// 如果设置里不开启称重水印，则text赋值为空字符串
				if (this.setting.Camera.openWatermark == false) {
					opt.text = ''
				}

				if (srcs.length == 0) {
					reject(photoArr)
				} else {
					camera.CapturePicture(
						srcs,
						20,
						opt.text,
						opt.textSize,
						(res) => {
							console.log('抓图成功：', res);
							res.forEach((item) => {
								photoArr.push(item.path)
							})
							resolve(photoArr)
						}, (err) => {
							console.log('抓图失败：', err);
							reject(err)
						}
					)
				}
			})
		},
		// 称重
		initWeigh() {
			// 磅秤初始化 
			console.log('开始匹配磅秤...')
			return new Promise((resolve, reject) => {
				Weigh.Start((openSuccess) => {
					console.log("磅秤已连接");
					console.log('getConfigProject', Weigh.getConfigProject());
					this.devices.Weigh.matched = true
					resolve()
				}, (fail) => {
					//数据回调失败 ，可能是数据格式错误
					console.log("数据回调失败", fail);
					this.devices.Weigh.matched = false
					this.devices.Weigh.isStable = false
					this.devices.Weigh.value = '--'
					reject(fail)
				}, (data) => {
					// console.log('磅秤数据成功回调:',data)
					this.devices.Weigh.value = data.Weight
					this.devices.Weigh.isStable = data.IsStable

				});
			})
		},
		// 关闭称重
		closeWeigh() {
			Weigh.Close()
		},
		// 磅秤归零
		Zeroing() {
			Weigh.Zeroing()
		},
		// 磅秤校准，传入实际的重量,单位KG
		Correction(number) {
			Weigh.Correction(number)
		},
		weighRestart() {
			Weigh.Restart()
		},
		// USB读卡器
		USBReadCard() {
			console.log('开始匹配usb读卡器...')
			return new Promise((resolve, reject) => {

				initUSBReadCard.Start((openmsg) => {
					resolve(openmsg)
					console.log('USB读卡器已打开', openmsg)
					this.devices.IC.matched = true
					this.setting.IC.matchCode = [openmsg]
					uni.setStorageSync('setting', this.setting)
				}, (code) => {
					console.log('USBReadCard:', code);
					this.devices.IC.value = code;
				}, (data) => {
					console.log('USB读卡器打开失败', data);
					this.devices.IC.matched = false
					reject(data)
					// this.setting.IC.chooseList = data
				})
			})
		},
		//USB扫码器
		USBScanCode() {
			console.log('开始匹配usb扫码器...')
			return new Promise((resolve, reject) => {

				initUSBScanCode.Start((openmsg) => {
					console.log('USB扫码器已打开', openmsg)
					resolve(openmsg)
					this.devices.ScanCode.matched = true
					this.setting.ScanCode.matchCode = [openmsg]
					uni.setStorageSync('setting', this.setting)
				}, (code) => {
					console.log('USBScanCode:', code);
					this.devices.ScanCode.value = code;
				}, (data) => {
					console.log('USB扫码器打开失败', data);
					this.devices.ScanCode.matched = false
					reject(data)
				});
			})
		},
		// 关闭usb读卡和扫码设备
		closeUsbAll() {
			initUSBReadCard.Close();
			initUSBScanCode.Close();
		},
		//发起打印
		Print(contentDataArr, isCheck = false) {
			console.log('正在打印...',contentDataArr)
			return new Promise((resolve, reject) => {
				let newArray = contentDataArr
				let headDataArr = [
					// {
					// 	method: "SetClean"//清理缓存，清除之前设置的参数
					// },
					// {
					// 	method: "SetReadZKmode", //设置汉字模式
					// 	param: [0]
					// },
					// {
					// 	/**
					// 	     * iWidth 宽度（1-8）
					// 	     * iHeight 高度（1-8）
					// 	*/
					// 	method: "SetSizetext" ,
					// 	param: [1,1]
					// },
				]
				let endDataArr = [
					// {
					// 	method: "PrintFeedline",
					// 	param: [6]
					// },
					// {
					// 	method: "PrintCutpaper", //打印切纸
					// 	param: [0]
					// }
				]

				// 是否换行
				let isPrintChargeRow = this.setting.Print.printChargeRow
				if (isPrintChargeRow == false) {
					newArray = newArray.filter((item) => item.method != 'PrintChargeRow')
					console.log('filterNewArray', newArray)
				}

				// 是否打印二维码
				let isPrintBase64Pic = this.setting.Print.printBase64Pic
				if (isPrintBase64Pic == false) {
					newArray = newArray.filter((item) => item.method != 'PrintBase64Pic')
				}

				let printData = [...headDataArr, ...newArray, ...endDataArr]
				console.log('打印命令：', printData)
				// 如果是检测打印机
				if (isCheck == true) {
					printData = []
				}
				startPrint(printData, (openSuccess) => {
					console.log("打印机已打开");
					this.devices.Print.matched = true
					// resolve()
				}, (openFail) => {
					console.log("打印机打开失败");
					this.devices.Print.matched = false
				}, (success) => {
					console.log("打印成功:" + JSON.stringify(printData));
					resolve(printData)
				}, (fail) => {
					console.log("打印失败:" + JSON.stringify(fail));
					reject(fail)
				});
			})
		},
		// 打开系统设置
		startToSet() {
			ToSet()
		}
	}
});

function getMac(){
	// 测试获取mac地址
	// #ifdef APP-PLUS
	// if(this.isDev){
	try {
		var net = plus.android.importClass("java.net.NetworkInterface");
		var wl0 = net.getByName('wlan0');
		var macByte = wl0.getHardwareAddress();
		
		var macStr = '';
		for (var i = 0; i < macByte.length; i++) {
			var tmp = "";
			var num = macByte[i];
			if (num < 0) {
				tmp = (255 + num + 1).toString(16);
			} else {
				tmp = num.toString(16);
			}
			if (tmp.length == 1) {
				tmp = "0" + tmp;
			}
			macStr += tmp + (i < macByte.length - 1 ? ":" : "");
		}
		console.log("MAC 地址:", macStr);
		return macStr
	} catch (error) {
		//TODO handle the exception
		return ""
	}
	
	// }
	// #endif
}